package com.itkm.service.impl;

import com.itkm.entity.Customer;
import com.itkm.service.CustomerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    private CustomerService customerService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Customer customer = customerService.getCustomer(username)
                .orElseThrow(() -> new UsernameNotFoundException("当前用户不存在：" + username));

        String authority = customerService.getCustomerAuthority(username);
        log.info("getCustomer {}", customer);

        return new User(customer.getUsername(), customer.getPassword(), Stream.of(authority)
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toSet())
        );
    }
}
